<template>
  <div class="schedule-manage">
    <!-- 编辑按钮 -->
    <div class="edit-button" v-if="isDeptManager">
      <el-button 
        type="primary" 
        :icon="Edit"
        @click="isEditing = !isEditing"
      >{{ isEditing ? '完成编辑' : '编辑排班' }}</el-button>
    </div>

    <!-- 员工列表区域 -->
    <div class="staff-list" v-if="isDeptManager && isEditing">
      <h4>部门员工</h4>
      <div class="staff-container">
        <div
          v-for="person in deptPersons"
          :key="person.personId"
          class="staff-item"
          draggable="true"
          @dragstart="handleDragStart($event, person)"
        >
          <el-tag>{{ person.personName }}</el-tag>
        </div>
      </div>
    </div>
    <!-- 查询区域 -->
    <el-form :inline="true" :model="searchForm" class="search-form" @submit.prevent>
      <el-form-item label="选择日期">
        <el-date-picker
          v-model="searchForm.date"
          :type="datePickerType"
          :placeholder="datePickerPlaceholder"
          value-format="YYYY-MM-DD"
          :default-value="new Date()"
        />
      </el-form-item>
      <el-form-item label="范围">
        <el-select v-model="searchForm.range" placeholder="选择范围" style="width: 100px;" @change="handleRangeChange">
          <el-option label="日视图" value="day" />
          <el-option label="周视图" value="week" />
          <el-option label="月视图" value="month" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchSchedules">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button-group>
          <el-button 
            v-if="searchForm.range === 'day'" 
            @click="adjustDate(-1)"
          >昨天</el-button>
          <el-button 
            v-if="searchForm.range === 'week'" 
            @click="adjustWeek(-1)"
          >上一周</el-button>
          <el-button 
            v-if="searchForm.range === 'month'" 
            @click="adjustMonth(-1)"
          >上一月</el-button>
          
          <el-button 
            v-if="searchForm.range === 'day'" 
            @click="adjustDate(1)"
          >明天</el-button>
          <el-button 
            v-if="searchForm.range === 'week'" 
            @click="adjustWeek(1)"
          >下一周</el-button>
          <el-button 
            v-if="searchForm.range === 'month'" 
            @click="adjustMonth(1)"
          >下一月</el-button>
        </el-button-group>
      </el-form-item>
      <el-form-item>
        <el-button v-if="userRole==='部门经理'" type="success" @click="handleAutoSchedule">自动排班</el-button>
      </el-form-item>
      <el-form-item label="只看我的" v-if="userRole==='普通操作人员'">
        <el-switch v-model="only_myself" />
      </el-form-item>
    </el-form>

    <!-- 日程表 -->
    <div v-if="scheduleData.schedules.length > 0">
      <h3>排班范围：{{ scheduleData.beginDate }} - {{ scheduleData.endDate }}</h3>
      <!-- 日视图 -->
      <div v-if="searchForm.range === 'day'" class="day-view">
        <el-card v-for="shift in ['早班', '中班', '晚班']" :key="shift" class="shift-card">
          <template #header>
            <div class="card-header">
              <span>{{ shift }}</span>
            </div>
          </template>
          <div 
            class="shift-content" 
            :class="{ editing: isEditing }"
            @dragover="handleDragOver" 
            @dragenter="handleDragEnter($event, searchForm.date, getShiftKey(shift))" 
            @dragleave="handleDragLeave" 
            @drop="handleDrop($event, searchForm.date, getShiftKey(shift))"
          >
            <template v-if="getDayShiftSchedules(getShiftKey(shift)).length > 0">
              <div v-for="item in getDayShiftSchedules(getShiftKey(shift))" :key="item.scheduleId" class="schedule-item">
                <el-descriptions :column="1" border>
                  <el-descriptions-item label="员工姓名">
                    <div class="schedule-person">
                      {{ item.personName }}
                      <el-button 
                        v-if="isDeptManager && isEditing" 
                        type="danger" 
                        link 
                        size="small" 
                        @click="handleDeleteSchedule(item.scheduleId)"
                      >移除</el-button>
                    </div>
                  </el-descriptions-item>
                  <el-descriptions-item label="状态">
                    <el-tag v-if="item.isLeave" type="warning">请假</el-tag>
                    <el-tag v-else type="success">正常</el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item v-if="item.isLeave && item.substitutePersonName" label="替班人">
                    {{ item.substitutePersonName }}
                  </el-descriptions-item>
                  <!-- 请假相关操作 -->
                  <el-descriptions-item v-if="!item.isLeave && item.personId === currentUser.personId" label="操作">
                    <el-button type="primary" link size="small" @click="handleApplyLeave(item)">申请请假</el-button>
                  </el-descriptions-item>
                  <el-descriptions-item v-if="isDeptManager && item.isLeave && !item.leaveApproved" label="操作">
                    <el-button type="primary" link size="small" @click="handleApproveLeave(item.scheduleId)">批准请假</el-button>
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </template>
            <div v-else class="no-schedule-message">拖入员工以添加排班</div>
          </div>
        </el-card>
      </div>
      <!-- 周视图 -->
      <el-table v-else-if="searchForm.range === 'week'" :data="formattedSchedules" border style="width: 100%" class="week-view-table">
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column v-for="shift in ['早班', '中班', '晚班']" :key="shift" :label="shift">
          <template #default="{ row }">
            <div 
              class="shift-content"
              :class="{ editing: isEditing }"
              @dragover="handleDragOver"
              @dragenter="handleDragEnter($event, row.date, getShiftKey(shift))"
              @dragleave="handleDragLeave"
              @drop="handleDrop($event, row.date, getShiftKey(shift))"
            >
              <template v-if="row.shifts[getShiftKey(shift)].length > 0">
                <div v-for="item in row.shifts[getShiftKey(shift)]" :key="item.scheduleId" class="schedule-item">
                  <div class="schedule-person">
                    {{ item.personName }}
                    <el-button 
                      v-if="isDeptManager && isEditing" 
                      type="danger" 
                      link 
                      size="small" 
                      @click="handleDeleteSchedule(item.scheduleId)"
                    >移除</el-button>
                  </div>
                  <div class="schedule-status">
                    <el-tag v-if="item.isLeave" :type="getTagType(item)" size="small">{{ item.isLeave ? (item.leaveApproved ? '已批准' : '未批准') : '' }}</el-tag>
                    <span v-if="item.isLeave && item.substitutePersonName"> (替班: {{ item.substitutePersonName }})</span>
                  </div>
                  <div class="schedule-actions">
                    <el-button 
                      v-if="!item.isLeave && item.personId === currentUser.personId" 
                      type="primary" 
                      link 
                      size="small" 
                      @click="handleApplyLeave(item)"
                    >申请请假</el-button>
                    <el-button 
                      v-if="isDeptManager && item.isLeave && !item.leaveApproved" 
                      type="primary" 
                      link 
                      size="small" 
                      @click="handleApproveLeave(item.scheduleId)"
                    >批准请假</el-button>
                  </div>
                </div>
              </template>
              <div v-else class="no-schedule-message">{{ isEditing ? '拖入员工以添加排班' : '暂无排班' }}</div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 月视图 -->
      <div v-else-if="searchForm.range === 'month'" class="month-view">
        <div class="calendar">
          <div class="calendar-header">
            <div v-for="day in ['一', '二', '三', '四', '五', '六', '日']" :key="day" class="calendar-cell header">
              {{ day }}
            </div>
          </div>
          <div class="calendar-body">
            <div v-for="week in monthCalendarData" :key="week[0].date" class="calendar-row">
              <div v-for="day in week" :key="day.date" class="calendar-cell" :class="{ 'other-month': !day.isCurrentMonth }">
                <div class="date-header">{{ new Date(day.date).getDate() }}</div>
                <div class="shifts-container">
                  <div 
                    v-for="shift in ['早班', '中班', '晚班']" 
                    :key="shift" 
                    class="shift-info"
                  :class="{ 
                    editing: isEditing, 
                    'morning-shift': shift === '早班',
                    'afternoon-shift': shift === '中班',
                    'night-shift': shift === '晚班'
                  }"
                  @dragover="handleDragOver"
                  @dragenter="handleDragEnter($event, day.date, getShiftKey(shift))"
                  @dragleave="handleDragLeave"
                  @drop="handleDrop($event, day.date, getShiftKey(shift))"
                  >
                    <template v-if="day.shifts && day.shifts[getShiftKey(shift)] && day.shifts[getShiftKey(shift)].length">
                      <div v-for="item in day.shifts[getShiftKey(shift)]" :key="item.scheduleId" class="person-tag">
                        <el-tooltip :content="getPersonTooltip(item)" placement="top">
                          <div class="schedule-person-month">
                            <el-tag :type="getTagType(item)" size="small">{{ item.personName }}</el-tag>
                            <el-button 
                              v-if="isDeptManager && isEditing" 
                              type="danger" 
                              link 
                              size="small" 
                              @click="handleDeleteSchedule(item.scheduleId)"
                            >×</el-button>
                          </div>
                        </el-tooltip>
                      </div>
                    </template>
                    <div v-else class="no-schedule-message-month">
                      <span v-if="isEditing">拖入员工</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-empty v-else description="暂无排班数据"></el-empty>

    <!-- 添加排班对话框 -->
    <el-dialog title="添加排班" v-model="showAddDialog" width="30%">
      <el-form>
        <el-form-item label="选择人员">
          <el-select v-model="selectedPersonId" placeholder="请选择人员" style="width: 100%">
            <el-option
              v-for="person in deptPersons"
              :key="person.personId"
              :label="person.personName"
              :value="person.personId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排班日期">
          <el-input :value="selectedDate" disabled />
        </el-form-item>
        <el-form-item label="班次">
          <el-input :value="selectedShift === 'morning' ? '早班' : selectedShift === 'afternoon' ? '中班' : '晚班'" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitSchedule">确定</el-button>
      </template>
    </el-dialog>

    <!-- 自动排班设置对话框 -->
    <el-dialog title="自动排班设置" v-model="showAutoScheduleDialog" width="40%">
      <el-form :model="autoScheduleForm" label-width="120px">
        <el-form-item label="每班人次">
          <el-input-number v-model="autoScheduleForm.shiftNum" :min="1" />
        </el-form-item>
        <el-form-item label="每人每天值班次数">
          <el-input-number v-model="autoScheduleForm.personalShiftNum" :min="1" />
        </el-form-item>
        <el-form-item label="周期内上班天数">
          <el-input-number v-model="autoScheduleForm.workDay" :min="1" />
        </el-form-item>
        <el-form-item label="周期内休息天数">
          <el-input-number v-model="autoScheduleForm.restDay" :min="0" />
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker v-model="autoScheduleForm.startDay" type="date" placeholder="选择开始日期" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker v-model="autoScheduleForm.endDay" type="date" placeholder="选择结束日期" value-format="YYYY-MM-DD" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAutoScheduleDialog = false">取消</el-button>
        <el-button type="primary" @click="submitAutoSchedule">确定</el-button>
      </template>
    </el-dialog>

    <!-- 申请请假对话框 -->
    <el-dialog title="申请请假" v-model="showLeaveDialog" width="30%">
      <el-form>
        <el-form-item label="排班日期">
          <el-input :value="selectedLeaveSchedule?.date" disabled />
        </el-form-item>
        <el-form-item label="班次">
          <el-input :value="selectedLeaveSchedule?.shift === '早' ? '早班' : selectedLeaveSchedule?.shift === '中' ? '中班' : '晚班'" disabled />
        </el-form-item>
        <el-form-item label="选择替班人">
          <el-select v-model="selectedSubstitutePersonId" placeholder="请选择替班人" style="width: 100%">
            <el-option
              v-for="person in deptPersons"
              :key="person.personId"
              :label="person.personName"
              :value="person.personId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showLeaveDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitLeave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';
import { Edit } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import dayjs from 'dayjs';
import { Plus, Delete } from '@element-plus/icons-vue';
import weekday from 'dayjs/plugin/weekday';
import { useUserStore } from '@/stores/user'

dayjs.extend(weekday);
dayjs.locale('zh-cn', { weekStart: 1 }); // 设置为中文环境，周一为一周的开始

// 从localStorage获取用户信息
const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}')
console.log(currentUser);
// 从Pinia获取用户信息
const userStore = useUserStore()
const userRole = computed(() => userStore.userInfo?.title || '普通操作人员')
const userId = computed(() => userStore.userInfo?.id || 0)
const userDeptId = computed(() => userStore.userInfo?.deptId || 0)

const isDeptManager = computed(() => userRole.value === '部门经理')
const isEditing = ref(false)

// 只看我的
const only_myself = ref(false);

// 排班相关
const calendarValue = ref(new Date());
const showAddDialog = ref(false)
const selectedDate = ref('')
const selectedShift = ref('')

// 自动排班相关
const showAutoScheduleDialog = ref(false)
const autoScheduleForm = reactive({
  shiftNum: 2,
  personalShiftNum: 2,
  workDay: 3,
  restDay: 1,
  startDay: dayjs().startOf('month').format('YYYY-MM-DD'),
  endDay: dayjs().endOf('month').format('YYYY-MM-DD'),
});

// 请假相关
const showLeaveDialog = ref(false)
const selectedLeaveSchedule = ref<ScheduleItem | null>(null)
const selectedSubstitutePersonId = ref('')

// 部门人员列表
const deptPersons = ref([])
const selectedPersonId = ref('')
const isDragging = ref(false)
const draggedPerson = ref(null)

// 获取部门人员列表
const fetchDeptPersons = async () => {
  try {
    const res = await axios.get(import.meta.env.VITE_API_URL + 'person/getByDept', {
      params: { deptId: userDeptId.value }
    })
    deptPersons.value = res.data
    
  } catch (error) {
    ElMessage.error('获取部门人员失败')
  }
}

// 拖拽相关方法
const handleDragStart = (event: DragEvent, person: any) => {
  isDragging.value = true
  draggedPerson.value = person
  if (event.dataTransfer) {
    event.dataTransfer.effectAllowed = 'move'
    event.dataTransfer.setData('text/plain', JSON.stringify(person))
  }
}

const handleDragEnter = (event: DragEvent, date: string, shift: string) => {
  event.preventDefault()
  const target = event.currentTarget as HTMLElement
  target.classList.add('dragover')
}

const handleDragLeave = (event: DragEvent) => {
  event.preventDefault()
  const target = event.currentTarget as HTMLElement
  target.classList.remove('dragover')
}

const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
}

const handleDrop = async (event: DragEvent, date: string, shift: string) => {
  event.preventDefault()
  const target = event.currentTarget as HTMLElement
  target.classList.remove('dragover')
  isDragging.value = false

  if (!draggedPerson.value) return

  try {
    const res = await axios.post(import.meta.env.VITE_API_URL + 'schedules/save', {
      deptId: userDeptId.value,
      personId: draggedPerson.value.personId,
      date: date,
      shift: shift === 'morning' ? '早' : shift === 'afternoon' ? '中' : '晚'
    })

    if (res.data) {
      ElMessage.success('排班成功')
      fetchSchedules()
    }
  } catch (error) {
    ElMessage.error('排班失败')
  }

  draggedPerson.value = null
}

// 添加排班
const handleAddSchedule = (date: string, shift: string) => {
  selectedDate.value = date
  selectedShift.value = shift
  showAddDialog.value = true
  fetchDeptPersons()
}

// 申请请假
const handleApplyLeave = (schedule: ScheduleItem) => {
  selectedLeaveSchedule.value = schedule
  showLeaveDialog.value = true
  fetchDeptPersons()
}

// 提交请假
const handleSubmitLeave = async () => {};

// 处理批准请假
const handleApproveLeave = async (scheduleId: number) => {
  try {
    await axios.put(`${import.meta.env.VITE_API_URL}schedules/reviewLeave/${scheduleId}?approved=true`);
    ElMessage.success('请假申请已批准');
    // 初始化数据
fetchSchedules();
fetchDeptPersons(); // 刷新排班数据
  } catch (error) {
    ElMessage.error('批准请假失败');
    console.error(error);
  }

  if (!selectedSubstitutePersonId.value) {
    ElMessage.warning('请选择替班人')
    return
  }
  if (!selectedLeaveSchedule.value) {
    ElMessage.error('请假信息错误')
    return
  }

  try {
    const res = await axios.post(import.meta.env.VITE_API_URL + 'schedules/applyLeave', {
      scheduleId: selectedLeaveSchedule.value.scheduleId,
      substitutePersonId: selectedSubstitutePersonId.value
    })

    if (res.data) {
      ElMessage.success('请假申请成功')
      showLeaveDialog.value = false
      selectedSubstitutePersonId.value = ''
      selectedLeaveSchedule.value = null
      fetchSchedules() // Refresh schedules to show leave status
    }
  } catch (error) {
    ElMessage.error('请假申请失败')
  }
}

// 提交排班
const handleSubmitSchedule = async () => {
  if (!selectedPersonId.value) {
    ElMessage.warning('请选择人员')
    return
  }

  try {
    const res = await axios.post(import.meta.env.VITE_API_URL + 'schedules/save', {
      deptId: userDeptId.value,
      personId: selectedPersonId.value,
      date: selectedDate.value,
      shift: selectedShift.value === 'morning' ? '早' : selectedShift.value === 'afternoon' ? '中' : '晚'
    })

    if (res.data) {
      ElMessage.success('排班成功')
      showAddDialog.value = false
      selectedPersonId.value = ''
      fetchSchedules()
    }
  } catch (error) {
    ElMessage.error('排班失败')
  }
}

// 自动排班
const handleAutoSchedule = () => {
  showAutoScheduleDialog.value = true;
  // 每次打开对话框时，重置表单数据为当前月份
  autoScheduleForm.startDay = dayjs().startOf('month').format('YYYY-MM-DD');
  autoScheduleForm.endDay = dayjs().endOf('month').format('YYYY-MM-DD');
};

// 提交自动排班
const submitAutoSchedule = async () => {
  try {
    const res = await axios.post(import.meta.env.VITE_API_URL + 'schedules/autoSchedule', {
      deptId: userDeptId.value,
      ...autoScheduleForm,
    });
    if (res.data) {
      ElMessage.success(res.data);
      showAutoScheduleDialog.value = false;
      // 初始化数据
fetchSchedules();
fetchDeptPersons();
    }
  } catch (error) {
    ElMessage.error('自动排班失败');
    console.error(error);
  }
};

// 删除排班
const handleDeleteSchedule = async (scheduleId: number) => {
  try {
    const res = await axios.delete(import.meta.env.VITE_API_URL + `schedules/${scheduleId}`)
    if (res.data) {
      ElMessage.success('删除成功')
      fetchSchedules()
    }
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

interface ScheduleItem {
  scheduleId: number;
  deptId: number;
  personId: number;
  date: string;
  shift: '早' | '中' | '晚';
  isLeave: boolean;
  leaveApproved: boolean;
  substitutePersonId: number;
  deptName: string;
  personName: string;
  substitutePersonName: string;
}

interface ScheduleData {
  deptName: string;
  range: 'day' | 'week' | 'month';
  schedules: ScheduleItem[][];
  beginDate: string;
  endDate: string;
}

const searchForm = reactive({
  date: dayjs().format('YYYY-MM-DD'),
  range: 'week' as 'day' | 'week' | 'month',
});

const datePickerType = computed(() => {
  const typeMap = {
    day: 'date',
    week: 'week',
    month: 'month'
  };
  return typeMap[searchForm.range];
});

const datePickerPlaceholder = computed(() => {
  const placeholderMap = {
    day: '选择日期',
    week: '选择周',
    month: '选择月'
  };
  return placeholderMap[searchForm.range];
});

const handleRangeChange = () => {
  // 切换范围时重置日期为当前日期
  searchForm.date = dayjs().format('YYYY-MM-DD');
};

// 监听查询条件变化
watch(
  () => [searchForm.date, searchForm.range],
  () => {
    // 初始化数据
fetchSchedules();
fetchDeptPersons();
  }
);

const getTagType = (item: ScheduleItem) => {
  if (item.isLeave) {
    return item.leaveApproved ? 'warning' : 'danger';
  }
  return 'success';
};

const getPersonTooltip = (item: ScheduleItem) => {
  let tooltip = `${item.personName}`;
  if (item.isLeave) {
    tooltip += ' (请假';
    tooltip += item.leaveApproved ? '已批准' : '未批准';
    if (item.substitutePersonName) {
      tooltip += `, 替班: ${item.substitutePersonName}`;
    }
    tooltip += ')';
  }
  return tooltip;
};

const monthCalendarData = computed(() => {
  if (!scheduleData.value || !scheduleData.value.schedules) return [];
  
  const currentMonth = dayjs(searchForm.date);
  const startOfMonth = currentMonth.startOf('month');
  const startOfCalendar = startOfMonth.weekday(0);
  const endOfMonth = currentMonth.endOf('month');
  const endOfCalendar = endOfMonth.weekday(6);
  
  const weeks = [];
  let currentDate = startOfCalendar;
  
  while (currentDate.isBefore(endOfCalendar) || currentDate.isSame(endOfCalendar, 'day')) {
    const week = [];
    for (let i = 0; i < 7; i++) {
      const date = currentDate.format('YYYY-MM-DD');
      const daySchedules = scheduleData.value.schedules.find(s => s[0]?.date === date) || [];
      week.push({
        date,
        isCurrentMonth: currentDate.isSame(currentMonth, 'month'),
        shifts: daySchedules.reduce((acc: any, schedule: ScheduleItem) => {
          const shiftKey = getShiftKey(getShiftLabel(schedule.shift));
          if (!acc[shiftKey]) acc[shiftKey] = [];
          acc[shiftKey].push(schedule);
          return acc;
        }, {})
      });
      currentDate = currentDate.add(1, 'day');
    }
    weeks.push(week);
  }
  return weeks;
});

const getShiftKey = (shift: string) => {
  const shiftMap = {
    '早班': 'morning',
    '中班': 'afternoon',
    '晚班': 'night'
  };
  return shiftMap[shift as keyof typeof shiftMap];
};

const getShiftLabel = (shift: string) => {
  const shiftMap = {
    '早': '早班',
    '中': '中班',
    '晚': '晚班'
  };
  return shiftMap[shift as keyof typeof shiftMap];
};

const getDayShiftSchedules = (shift: string) => {
  if (scheduleData.value.schedules.length === 0) return [];
  const shiftMap = { 'morning': '早', 'afternoon': '中', 'night': '晚' };
  return scheduleData.value.schedules[0].filter(item => item.shift === shiftMap[shift as keyof typeof shiftMap]);
};

const scheduleData = ref<ScheduleData>({
  deptName: '',
  range: 'week',
  schedules: [],
  beginDate: '',
  endDate: '',
});

// 日期调整方法
const adjustDate = (days: number) => {
  searchForm.date = dayjs(searchForm.date).add(days, 'day').format('YYYY-MM-DD');
  // 初始化数据
fetchSchedules();
fetchDeptPersons();
};

const adjustWeek = (weeks: number) => {
  searchForm.date = dayjs(searchForm.date).add(weeks, 'week').format('YYYY-MM-DD');
  // 初始化数据
fetchSchedules();
fetchDeptPersons();
};

const adjustMonth = (months: number) => {
  searchForm.date = dayjs(searchForm.date).add(months, 'month').format('YYYY-MM-DD');
  // 初始化数据
fetchSchedules();
fetchDeptPersons();
};

const fetchSchedules = async () => {
  if (!searchForm.date) {
    ElMessage.warning('请选择日期');
    return;
  }
  try {
    const response = await axios.get(`${import.meta.env.VITE_API_URL}schedules/getSchedules`, {
      params: {
        date: searchForm.date,
        range: searchForm.range,
        deptId: userDeptId.value,
        personId: only_myself.value ? userDeptId.value : null
      },
    });
    const data = response.data;
    const currentDate = dayjs(searchForm.date);
    if (searchForm.range === 'month') {
      data.beginDate = currentDate.startOf('month').format('YYYY-MM-DD');
      data.endDate = currentDate.endOf('month').format('YYYY-MM-DD');
    } else if (searchForm.range === 'week') {
      data.beginDate = currentDate.weekday(0).format('YYYY-MM-DD');
      data.endDate = currentDate.weekday(6).format('YYYY-MM-DD');
    } else if (searchForm.range === 'day') {
      data.beginDate = currentDate.format('YYYY-MM-DD');
      data.endDate = currentDate.format('YYYY-MM-DD');
    }
    scheduleData.value = data;
  } catch (error) {
    ElMessage.error('获取排班数据失败');
    console.error(error);
    scheduleData.value = {
      deptName: '',
      range: searchForm.range,
      schedules: [],
      beginDate: '',
      endDate: '',
    };
  }
};

const formattedSchedules = computed(() => {
  if (!scheduleData.value || !scheduleData.value.schedules) {
    return [];
  }
  let dailySchedules: ScheduleItem[][] = [];
  if (scheduleData.value.range === 'day' && scheduleData.value.schedules.length > 0 && !Array.isArray(scheduleData.value.schedules[0])) {
    dailySchedules = [scheduleData.value.schedules as ScheduleItem[]];
  } else {
    dailySchedules = scheduleData.value.schedules;
  }
  return dailySchedules.map((daySchedule, index) => {
    const date = dayjs(scheduleData.value.beginDate).add(index, 'day').format('YYYY-MM-DD');
    const shifts = {
      morning: daySchedule.filter(item => item.shift === '早'),
      afternoon: daySchedule.filter(item => item.shift === '中'),
      night: daySchedule.filter(item => item.shift === '晚'),
    };
    return { date, shifts };
  });
});

const monthTableData = computed(() => {
  if (scheduleData.value.range !== 'month' || !scheduleData.value.schedules) return [];
  let dailySchedules: ScheduleItem[][] = scheduleData.value.schedules;
  return dailySchedules.map((daySchedule, index) => {
    const date = dayjs(scheduleData.value.beginDate).add(index, 'day').format('YYYY-MM-DD');
    const shifts = {
      morning: daySchedule.filter(item => item.shift === '早'),
      afternoon: daySchedule.filter(item => item.shift === '中'),
      night: daySchedule.filter(item => item.shift === '晚'),
    };
    return { date, shifts };
  });
});

// 初始化数据
fetchSchedules();
fetchDeptPersons();
</script>

<style scoped>
.staff-list {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.staff-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.staff-item {
  cursor: move;
  transition: transform 0.2s;
}

.staff-item:hover {
  transform: translateY(-2px);
}

.edit-button {
  margin-bottom: 20px;
}

.shift-content {
  min-height: 100px;
  padding: 10px;
  border-radius: 4px;
  transition: all 0.3s;
}

.shift-content:not(.editing) {
  border: 1px solid transparent;
}

.shift-content.editing {
  border: 1px dashed #dcdfe6;
}

.shift-content.dragover {
  background-color: #ecf5ff;
  border-style: solid;
  border-color: #409eff;
  transform: scale(1.01);
}

.schedule-person {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.schedule-person-month {
  display: flex;
  align-items: center;
  gap: 4px;
}

.schedule-status {
  margin: 4px 0;
}

.schedule-actions {
  display: flex;
  gap: 8px;
  margin-top: 4px;
}

.shift-info {
  min-height: 24px;
  padding: 2px 4px;
  border-radius: 2px;
  margin-bottom: 2px;
  transition: all 0.3s;
}

.shift-info:not(.editing) {
  border: 1px solid transparent;
}

.shift-info.editing {
  border: 1px dashed #dcdfe6;
}

.shift-info.dragover {
  background-color: #ecf5ff;
  border-style: solid;
  border-color: #409eff;
}

/* 班次样式 */
.morning-shift {
  background-color: #e6f7ff;
  border-left: 3px solid #1890ff;
}

.afternoon-shift {
  background-color: #fff7e6;
  border-left: 3px solid #fa8c16;
}

.night-shift {
  background-color: #f9f0ff;
  border-left: 3px solid #722ed1;
}

.no-schedule-message,
.no-schedule-message-month {
  color: #909399;
  font-size: 14px;
  text-align: center;
  margin-top: 10px;
}

.no-schedule-message-month {
  font-size: 12px;
  margin-top: 5px;
}

.calendar {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fff;
}

.calendar-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.calendar-body {
  display: flex;
  flex-direction: column;
}

.calendar-row {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-auto-rows: minmax(120px, auto); /* Set minimum height and allow growth */
}

.calendar-cell {
  padding: 4px; /* Reduce padding */
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
  box-sizing: border-box;
  overflow: hidden; /* Hide overflow for the cell */
  display: flex;
  flex-direction: column;
}

.calendar-cell.header {
  min-height: auto;
  padding: 12px;
  text-align: center;
  font-weight: bold;
}

.calendar-cell:last-child {
  border-right: none;
}

.calendar-row:last-child .calendar-cell {
  border-bottom: none;
}

.other-month {
  background-color: #f9f9f9;
  color: #909399;
}

.date-header {
  font-size: 14px; /* Reduce font size */
  font-weight: bold;
  margin-bottom: 4px; /* Reduce margin */
  color: #606266;
}

.shifts-container {
  display: flex;
  flex-direction: column;
  gap: 2px; /* Reduce gap */
  flex-grow: 1; /* Allow container to grow */
  overflow-y: auto; /* Allow vertical scrolling */
  padding-right: 4px; /* Add some padding for scrollbar */
}

.shift-info {
  display: flex;
  flex-direction: column; /* Stack shift info vertically */
  gap: 4px;
}

.person-tag {
  margin: 0;
}

.day-view {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.shift-card {
  flex: 1;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.schedule-item {
  margin-bottom: 15px;
}

.schedule-item:last-child {
  margin-bottom: 0;
}

.month-view {
  margin-top: 20px;
}

/* Week View Specific Styles */
.week-view-table .shift-content {
  display: flex;
  flex-direction: column;
  gap: 8px; /* Add some space between button and items */
}

.week-view-table .shift-content .el-button {
  align-self: flex-start; /* Align button to the start */
  margin-bottom: 4px; /* Add space below the button */
}

.week-view-table .schedule-item p {
  display: flex;
  align-items: center;
  gap: 4px; /* Space between elements in the paragraph */
  flex-wrap: wrap; /* Allow wrapping */
  margin: 0; /* Remove default paragraph margin */
}

.week-view-table .schedule-item .el-button {
  margin-left: auto; /* Push delete button to the right */
}
</style>